import * as API from '@/api/dataBoard';
import { ref, reactive, onBeforeMount, watch,onUnmounted } from 'vue';
const getMax = (_data: any) => {
  let total = 0;
  _data.forEach((item: any) => {
    total += item.value;
  });
  return total;
}
const keys = ['PH值', '化学需氧量', '氨氮用量', '非甲烷总烃'];

export default () => {
  let dateType = ref('day')
  let current = ref([]);
  let alarm = ref([]);
  let sort = reactive([]);
  let timmer: any = null;
  const getEnvironmentCurrent = async () => {
    const res = await API.getEnvironmentCurrent();
    if (res) {
      const arr: any = [];
      res.forEach((target) => {
        const index = keys.indexOf(target.classifyName);
        if (index!==-1) {
          arr[index] = {
            ...target,
            classifyName: target.classifyName.includes('氨氮') ? '氨氮' : target.classifyName
          };
        }
      });
      current.value = arr;
    }
  }
  const getEnvironmentSort = async () => {
    const res = await API.getEnvironmentSort({
      dateType: dateType.value
    });
    if (res) {
      const _data = res.energyTrend;
      Object.keys(_data).forEach((key, index) => {
        const _index = keys.indexOf(key);
        if (_index !== -1) {
          sort[_index]=_data[key];
        }
        
      });
    }
  }
  const getEnvironmentAlarm = async () => {
    const res = await API.getEnvironmentAlarm();
    if (res) {
      alarm.value = res;
    }
  }
  watch(dateType, () => {
    getEnvironmentSort();
  })
  onBeforeMount(() => {
    getEnvironmentCurrent();
    getEnvironmentSort();
    getEnvironmentAlarm();
    // 定时拉取
    // timmer = setInterval(() => {
    //   getEnvironmentCurrent();
    //   getEnvironmentAlarm();
    // },10000);
  })
  onUnmounted(() => {
    clearInterval(timmer);
  })
  return {
    current,
    alarm,
    sort,
    dateType
  }
}